package cn.com.dhcc.turbo.web.controller.monitor;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.JsonUtil;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.app.pub.core.consts.KernelParam;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.app.pub.core.util.fusioncharts.Categories;
import cn.com.dhcc.app.pub.core.util.fusioncharts.Category;
import cn.com.dhcc.app.pub.core.util.fusioncharts.Chart;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartDataset;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartSet;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartXmlUtil;
import cn.com.dhcc.turbo.entity.exch.NodeLayout;
import cn.com.dhcc.turbo.entity.monitor.MonitorShowVO;
import cn.com.dhcc.turbo.entity.monitor.QuotaValueOnTime;
import cn.com.dhcc.turbo.entity.registry.AdapterInfo;
import cn.com.dhcc.turbo.entity.registry.DomainInfo;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.service.exch.ExchRelService;
import cn.com.dhcc.turbo.service.monitor.CrossNetMonitorService;
import cn.com.dhcc.turbo.service.monitor.MonitorService;
import cn.com.dhcc.turbo.service.monitor.MonitorVO;
import cn.com.dhcc.turbo.service.monitor.PendingVo;
import cn.com.dhcc.turbo.service.registry.AdapterInfoService;
import cn.com.dhcc.turbo.service.registry.DomainInfoService;
import cn.com.dhcc.turbo.service.registry.MonitorQuotaService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;

@Controller
@RequestMapping("/monitor")
public class MonitorController extends BaseController {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.TURBO);
	@Autowired
	MonitorService monitorService;
	@Autowired
	private NodeInfoService nodeService;
	
	@Autowired
	private MonitorQuotaService mqService;
	@Autowired
	private DomainInfoService doMainService;
	@Autowired
	private ExchRelService exchRelService;
	@Autowired
	CrossNetMonitorService crossNetMonitorService;
	@Autowired
	AdapterInfoService adapterService;
	/**
	 * 实时监控首页
	 * 
	 * @return
	 */
	@TurboMenu(belongToMenu = LEAF_MENU.MONITOR_ONTIME)
	@RequestMapping("ontime")
	public String ontime(Model model,HttpSession httpSession) {
		try {
			//本地節點信息
			NodeInfo node = nodeService.getLocalNode();
			List<AdapterInfo> adapterList = adapterService.getLocalAdapterList();
			List<DomainInfo> domainList= doMainService.getLocalDomain();
			UserInfo user = (UserInfo)getCurrentUserInfo(httpSession);
			if(user != null){
				model.addAttribute("nodeAdmin", user.getUserType());
				model.addAttribute("ownId", user.getOwnId());
				if(user.getUserType().equals("0")){
					model.addAttribute("searchType", "adapter");
				}else{
					model.addAttribute("adapterList", adapterList);
					model.addAttribute("domainList", domainList);
				}
			}
			int tlqEnable = KernelParam.tlqTransportPipelineEnable;
			model.addAttribute("node", node);
			model.addAttribute("tlqEnable", tlqEnable);
			model.addAttribute("hasGap", NodeInfoParam.hasGap);
		} catch (ServiceException e) {
			logger.error(e);
		}
		return "monitor/monitor_ontime";
	}

	/**
	 * 节点基本信息监控
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("node_monitor")
	public Map<String, Object> nodeInfoMonitor(String nodeId) {
		try {
			MonitorVO monitorVO = monitorService.getNodeMonitor(nodeId);
				
			return jsonSuccessDataResult("", monitorVO);
		} catch (NiceException e) {
			return jsonFailResult(e.getMessage());
		} catch (Exception e) {
			return jsonFailResult("获取节点基本监控信息失败!");
		}
	}

	/**
	 * 节点通道信息监控
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("pipeline_monitor")
	public Map<String, Object> pipeLineMonitor() {
		return null;
	}

	/**
	 * 发货，收货量监控
	 * 
	 * @param type
	 *            1 发送 2 接收
	 * @return
	 */
	@ResponseBody
	@RequestMapping("flow_monitor")
	public Map<String, Object> flowMonitor(int type) {
		return null;
	}

	/**
	 * 结构化数据发送监控统计
	 * 
	 * @param type
	 *            1 发送 2 接收
	 * @param level
	 *            1 按节点 2 按域 3 按系统
	 * @return
	 */
	@ResponseBody
	@RequestMapping("structured_monitor")
	public Map<String, Object> structuredMonitor(int type, int level) {
		return null;
	}

	/**
	 * 非结构化数据发送监控统计
	 * 
	 * @param type
	 *            1 发送 2 接收
	 * @param level
	 *            1 按节点 2 按域 3 按系统
	 * @return
	 */
	@ResponseBody
	@RequestMapping("unstructured_monitor")
	public Map<String, Object> unstructuredMonitor(int type, int level) {
		return null;
	}

	/**
	 * 数据发送量实时监控
	 * 
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("statistics_monitor")
	public Map<String, Object> statisticsMonitor(Model model,String type,String level,String ownerId) {
		String msg = "";
		try {
			List<QuotaValueOnTime> unStructuredList1 = monitorService.getSendFlowHourList("unstructured_send_flow_hour_for_"+level,ownerId);// 非常规数据发送量
			List<QuotaValueOnTime> unStructuredList2 = monitorService.getSendFlowHourList("unstructured_recv_flow_hour_for_"+level,ownerId);// 非常规数据发送量
			
			Chart chart = new Chart();
			chart.setShowValues("0");
			chart.setExtProperty("caption='数据交换' yAxisMinValue='1'  labelDisplay='Rotate' slantLabels='1' rotateNames='0' bgColor='FFFFFF' numdivlines='9' lineThickness='2' showValues='0' anchorRadius='3'	anchorBgAlpha='50' showAlternateVGridColor='1' numVisiblePlot='12' animation='1' shadowAlpha='100' showborder='0'");
			Categories categories = new Categories();
			List<Category> cList = new ArrayList<Category>();
			for (Iterator<QuotaValueOnTime> iterator = unStructuredList1.iterator(); iterator.hasNext();) {
				QuotaValueOnTime vo = iterator.next();
				Category c0 = new Category();
				c0.setLabel(vo.getStime());
				cList.add(c0);
			}
			categories.setCategory(cList);
			chart.setCategories(categories);
			List<ChartDataset> dList = new ArrayList<ChartDataset>();
			ChartDataset d1 = new ChartDataset();
			d1.setSeriesName("发送");
			d1.setColor("800080");
			d1.setAnchorBorderColor("800080");
			List<ChartSet> sets1 = new ArrayList<ChartSet>();
			for (Iterator<QuotaValueOnTime> iterator = unStructuredList1.iterator(); iterator.hasNext();) {
				QuotaValueOnTime quota =  iterator.next();
				ChartSet set = new ChartSet();
				set.setValue(quota.getSumval());
				sets1.add(set);
			}
			
			
			ChartDataset d3 = new ChartDataset();
			d3.setSeriesName("接收");
			d3.setColor("FFFF00");
			d3.setAnchorBorderColor("FFFF00");
			List<ChartSet> sets3 = new ArrayList<ChartSet>();
			for (Iterator<QuotaValueOnTime> iterator = unStructuredList2.iterator(); iterator.hasNext();) {
				QuotaValueOnTime quota =  iterator.next();
				ChartSet set = new ChartSet();
				set.setValue(quota.getSumval());
				sets3.add(set);
			}
			d1.setSet(sets1);
			d3.setSet(sets3);
			dList.add(d1);
			dList.add(d3);
			chart.setDataset(dList);
			msg = ChartXmlUtil.forXML(chart);
			return jsonSuccessDataResult("success", msg);
		} catch (Exception e) {
			msg = "数据发送量实时监控失败";
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	@RequestMapping(value = "/get_monitor_show")
	@ResponseBody
	public Map<String, Object> getMonitorShow(String codes,String ownerId) {
		String msg = "";
		try {
			if(codes == null || codes.length() == 0 || "".equals(codes)){
				return jsonSuccessResult(msg);
			}
			List<MonitorShowVO> ms= mqService.getMonitorShow(codes.split(","),ownerId);
			msg = JsonUtil.toJson(ms);
			return jsonSuccessResult(msg);
		} catch (Exception e) {
			msg = "获取监控指标信息失败";
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	/**
	 * 获取未处理告警和待审核数量
	 * @param codes
	 * @param ownerId
	 * @return
	 */
	@RequestMapping(value = "/load_data")
	@ResponseBody
	public Map<String, Object> loadData(String[] codes,String ownerId,HttpSession httpSession) {
		String msg = "";
		try {
			UserInfo userInfo = (UserInfo)super.getUserSessionVo(httpSession);
			NodeInfo localNode = nodeService.getLocalNode();
			PendingVo req = new PendingVo();
			req.setCode("carvedDiscsSumReq");
			PendingVo alert = new PendingVo();
			alert.setCode("countAlert");
			if(localNode != null && userInfo != null){
				String code[]={"carved_discs_sum"};
				List<MonitorShowVO> ms= mqService.getMonitorShow(code,localNode.getId());
				if(ms.size()>0){
					req.setValue(Integer.parseInt(ms.get(0).getValue()));
				}else{
					req.setValue(0);
				}
				if("4".equals(userInfo.getSlAuthFlag())){
					alert.setValue(monitorService.getCountAlert(userInfo.getOwnId()));
				}else{
					alert.setValue(monitorService.getCountAlert(""));
				}
			}else{
				req.setValue(0);
				alert.setValue(0);
			}
			List<PendingVo> list = new ArrayList<PendingVo>();
			list.add(req);
			list.add(alert);
			msg = JsonUtil.toJson(list);
			return jsonSuccessResult(msg);
		} catch (Exception e) {
			msg = "获取监控指标信息失败";
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	/**
	 *
	 * 获取监控关系图:管理范围内全部节点
	 * @param model
	 * @param response
	 */
	@RequestMapping(value = "/get_node_layout")
	public void getNodeLayout(Model model,HttpServletResponse response) {
		try {
			String  rstVal= monitorService.getAllNodeLayout();
			//结果数据输出
			OutputStream outputStream = response.getOutputStream();
			response.setContentType("text/xml;charset=UTF-8");
			FileCopyUtils.copy(rstVal, new OutputStreamWriter(outputStream, "UTF-8"));
			outputStream.flush();
			response.flushBuffer();
			if (outputStream != null)
				outputStream.close();
		} catch (Exception e) {
			logger.error("获取监控关系图失败", e);
		}
	}
	
	/**
	 * 获取监控关系图：显示与本节点有交换关系的节点
	 * @param model
	 * @param response
	 */
	@RequestMapping(value = "/get_node_layout_local")
	public void getNodeLayoutLocal(Model model,HttpServletResponse response) {
		try {
			NodeInfo localNode = nodeService.getLocalNode();
			NodeLayout nodeLayout = exchRelService.getNodeLayout(localNode.getId());
			String  rstVal = monitorService.forExchRelXML(localNode.getId(), nodeLayout.getRelNodeLayout());
			//结果数据输出
			OutputStream outputStream = response.getOutputStream();
			response.setContentType("text/xml;charset=UTF-8");
			FileCopyUtils.copy(rstVal, new OutputStreamWriter(outputStream, "UTF-8"));
			outputStream.flush();
			response.flushBuffer();
			if (outputStream != null)
				outputStream.close();
		} catch (Exception e) {
			logger.error("获取监控关系图失败", e);
		}
	}
	
	@RequestMapping(value = "/get_node")
	public void getNode(Model model,HttpServletResponse response,String nodeId){
		try {
			if(nodeId == null){
				return;
			}
			//封装xml格式数据
			String  rstVal =monitorService.getNode(nodeId);
			//结果数据输出
			OutputStream outputStream = response.getOutputStream();
			response.setContentType("text/xml;charset=UTF-8");
			FileCopyUtils.copy(rstVal, new OutputStreamWriter(outputStream, "UTF-8"));
			outputStream.flush();
			response.flushBuffer();
			if (outputStream != null)
				outputStream.close();
		} catch (Exception e) {
			logger.error("获取节点信息失败", e);
		}
	}
	@RequestMapping(value = "/get_line")
	public void getLine(Model model,HttpServletResponse response,String fromNodeId,String toNodeId){
		try {
			String  rstVal =monitorService.getLine(fromNodeId,toNodeId);
			//结果数据输出
			OutputStream outputStream = response.getOutputStream();
			response.setContentType("text/xml;charset=UTF-8");
			FileCopyUtils.copy(rstVal, new OutputStreamWriter(outputStream, "UTF-8"));
			outputStream.flush();
			response.flushBuffer();
			if (outputStream != null)
				outputStream.close();
		} catch (Exception e) {
			logger.error("获取通道信息失败", e);
		}
	}
	
}
